<?php
namespace app\controllers; //命名空间

use yii\web\Controller; // 导入Controller
use app\controllers\BaseController; //导入基础controller（内含各种基础使用函数）

use app\models\User; //用户模型
use app\models\UserCommic; //用户收藏漫画模型
use app\models\CommicType; //漫画类型模型
use app\models\Commic; //漫画模型
use app\models\CommicRecord; //漫画记录模型
use app\models\CommicPages;

use yii\web\Session;
use Yii; // 导入Yii
/****
漫画有关功能：
1、显示：全部显示(按照最新更新时间)
        排行榜显示、（阅读量、收藏量）
        类型显示、
        更新显示、
        推荐显示（以当天更新且热度高的前三个漫画为例）、
2、搜索：名字搜索、
3、用户收藏：收藏功能、
            观看收藏内容(按照更新时间排序)
4、阅读历史：内容：{阅读集页、阅读时间}
****/
/***
单一url的参数设置：
主函数index:
showall
loadcom
showtop
showtype
showupdate
showtopthree
***/

class CommicController extends Controller{
    //在Yii框架中，为了防止csrf攻击，封装了CSRF令牌验证
    public $enableCsrfValidation = false;

	//总函数 经商讨 使用关键字返回的形式那么
	public function actionIndex(){
		//根据参数返回来确定功能 详细参数看注释
        if( Yii::$app->request->isPost ){
            //数据初始化
            //负责调用全部action函数的单一函数
            /*
              Showall       显示全部漫画关键字                    
              Showrank      显示排行榜包括阅读量、收藏量          
              Showcom       显示单一漫画                      
              Showtype      显示单一类型的漫画 
              Showcconfig   显示全部类型
              Showupdate    显示最新更新的漫画
              Showtopthree  显示收藏量top3的漫画
              Collect       用户功能：收藏
              Uncollect     用户功能：取消收藏
              Showcollect   用户功能：查看全部收藏
              Showhistory   用户功能：阅读历史
              Reading       用户功能：记录用户阅读历史、漫画阅读量
            */ 
            $postData = Yii::$app->request->post(); //接收function
            $function = $postData['function'];
            switch ($function) {
                case 'Showall':
                    $data = $this->function_Showall();      //不需要任何参数
                    break;

                case 'Showfindcom':
                    $data = $this->function_Showfindcom($postData);  //需要参数'cName'
                    break;

                case 'Showrank':
                    $data = $this->function_Showrank($postData);     //需要的参数的'rank' : 'collection' / 'read'
                    break;

                case 'Showcom':
                    $data = $this->function_Showcom($postData);      //需要的参数为 'cId'、'session' : '有'或者'NULL'
                    break;

                case 'Showtype':
                    $data = $this->function_Showtype($postData);     //需要的参数 cTid
                    break;

                case 'Showcconfig':
                    $data = $this->function_Showcconfig();  //不需要参数
                    break;

                case 'Showtopthree':
                    $data = $this->function_Showtopthree();  //不需要参数
                    break;

                case 'Showupdate':
                    $data = $this->function_Showupdate();    //不需要参数
                    break;

                case 'Collect':
                    $data = $this->function_Collect($postData);       //需要的参数session
                    break;

                case 'Uncollect':
                    $data = $this->function_Uncollect($postData);     //需要的参数cId、session
                    break;

                case 'Showcollect':
                    $data = $this->function_Showcollect($postData);   //需要参数session
                    break;

                case 'Showhistory':
                    $data = $this->function_Showhistory($postData);   //需要的参数session
                    break;

                case 'Reading':
                    $data = $this->function_Reading($postData);       //需要的参数session、cId、reading
                    break;
                default:
                    $content = '不存在此种功能';
                    $data = array(
                        '0' => 0,
                        '1' => $content,
                    );
                    return BaseController::FailRespone($data);
                    break;
            }
            return BaseController::EveryResponse($data);
            exit(0);
        }else{
            $content = "接收的posts数据为空";
            $data = array(
                '0' => -2,
                '1' => $content,
            );
            return BaseController::FailRespone($data);   
        }
        exit(0);
	}

	//漫画全部显示
	//漫画储存在服务器上 
	//这边主要储存路径
	//此外做一个上传的函数
	//业务逻辑：先显示所有漫画（形式为最新更新的漫画）返回的形式以数组形式返回 --- 
    //数组形式为 {
    //           [0]:{
    //                ['cId']:...漫画id
    //                ['cCover']:..封面
    //                ['cName']:..名称
    //                ['cAuthor']:..作者
    //                }
    //           [1]:{
	//                与上类似
	//               }
    //            }
    //当确定某漫画时就返回详细名称从而返回集数
	public function function_Showall(){ //不需要任何参数
		$type = new CommicType();
            //数据初始化
        $commics = Commic::getAll();
        if(empty($commics)){
        	$content = '数据错误，没有搜到任何漫画';
        	$data = array(
                '0' => -3, 
                '1' => $content,
            );
            return $data;
        }
        $data = array(
            '0' => 1,
            '1' => $commics,
        );
        return $data;
	}

    //全局查找，根据关键字查找漫画
    public function function_Showfindcom($postData){ //需要参数'cName'
        if(empty($postData['cName'])){
            //当没有uId时的报错返回
            $content = "请输入你要查找的漫画";
            $data = array(
                '0' => -3,
                '1' => $content,
            );
            return $data;
        }
        //数据初始化
        //接收数据
        $cName = $postData['cName'];
        //查找
        $search_result = Commic::getSearch($cName);
        if(!$search_result){
            //当没有uId时的报错返回
            $content = "查询不到你要的漫画";
            $data = array(
                '0' => 0,
                '1' => $content,
            );
            return $data;
        }
        $data = array(
            '0' => 1,
            '1' => $search_result,
        );
        return $data;
    }

	//漫画排行榜显示（两个参数-阅读量、收藏量）//前10 或前20 
	public function function_Showrank($postData){ //需要的参数的'rank' : 'collection' / 'read'
        //数据初始化
        //接收数据
		$rank = $postData['rank'];  //参数为 collection read
		if($rank == 'collection'){
			$commics = Commic::getBycollection();
		}else if($rank == 'read'){
			$commics = Commic::getByreadcount();
		}
		if(empty($commics)){
			$content = '暂时没查到任何漫画';
			$data = array(
                '0' => 0, 
                '1' => $content,
            );
            return $data;
		}
        $data = array(
            '0' => 1,
            '1' => $commics,
        );
		return $data;
	}

    //数组：array{ 'cId','cName','cAuthor','cCover','cCollection','cReadcount','cSaveurl','cNowupdate','cUpdatetime','collect'} //封面，名字，作者，储存路径，最新集数，
    //那么可更据最新集数来 输出油1～最新集数的图片 https://193.112.72.237/Commics/神秘的程序员/1/1.jpg
	//看详细某一部漫画
    //商量 是前端使用逻辑 还是后端返回集数 然后返回逻辑

    #*****增加一个此漫画观看到某一部分逻辑
	public function function_Showcom($postData){ //需要的参数为 'cId'、'session' : '有'或者'NULL'
        //判断数据是否齐全
        if(empty($postData['cId'])){
             //当没有uId时的报错返回
            $content = "请输入cId";
            $data = array(
                '0' => -3,
                '1' => $content,
            );
            return $data;
        }else if (empty($postData['session'])) {
            $postData['session'] = NULL;
        }
        //数据初始化
        //接收数据
        $cId = $postData['cId'];  //参数为 cId 漫画的id
        $session = $postData['session']; //有登录传session 没登录传null
        $uId = BaseController::Check_session($session); //检查是否登录
        if(empty($cId)){
            $content = '请输入cId';
            $data = array(
                '0' => 0, 
                '1' => $content,
            );
            return $data;
        }
        //查找漫画详细信息
        $commic_info = Commic::getBycId($cId);
        if(!isset($commic_info)){
            $content = '暂时未找到漫画';
            $data = array(
                '0' => 0, 
                '1' => $content,
            );
            return $data;
        }
        //检查漫画是否被用户所收藏
        if(!$uId){
            $commic_info['collect'] = false;
        }else{
            $user_commic_info = array(
                'uId' => $uId,
                'cId' => $cId,
            );
            $check_result = UserCommic::checkByuIdcId($user_commic_info);
            $commic_info['collect'] = $check_result;
        }
        //储存路径
        $saveurl = $commic_info['cSaveurl'];
        //所拥有的集数
        $episodes = $commic_info['cNowupdate'];
        //漫画集数及其储存路径
        $episodes_info = $this->Deal_episode($cId, $saveurl, $episodes);
        if(!$episodes_info){
            $content = '暂时未找到漫画';
            $data = array(
                '0' => 0, 
                '1' => $content,
            );
            return $data;
        }
        //查看此漫画阅读历史
        $user_record = CommicRecord::getHisByuIdcId($uId, $cId);
        if(!empty($user_record)){
            $commic_info['history']['read'] = true;
            $commic_info['history']['readagain'] = $this->Deal_OneCommicRecord($user_record);
        }else{
            //创建新的阅读历史
            $new_record = array(
                'cId' => $cId,
                'uCReading' => '1/1',
            );
            $commic_info['history']['read'] = false;
            $commic_info['history']['readagain'] = $this->Deal_OneCommicRecord($new_record);
        }
        //漫画集数的详细信息
        $commic_info['episodes_info'] = $episodes_info;
        //查看用户对于此漫画阅读历史
        $data = array(
            '0' => 1,
            '1' => $commic_info,
        );
        return $data;
	}
    
    //独立一个接口
	//漫画类型显示
	public function function_Showtype($postData){ //需要的参数 cTid
        //数据初始化
        //接收数据
		$cTid = $postData['cTid'];
		$commics = Commic::getBytype($cTid);
		if(empty($commics)){
			$content = '暂时没查到任何这种类型漫画';
			$data = array(
                '0' => 0, 
                '1' => $errorContent,
            );
            return $data;
		}
        $data = array(
            '0' => 1,
            '1' => $commics,
        );
		return $data;
	}

	//漫画类型显示
	public function function_Showcconfig(){  //不需要参数
		$types = CommicType::getAlltype();
        $data = array(
            '0' => 1,
            '1' => $types,
        );
		return $data;
	}

    //推荐漫画显示（前三）首页 滚动页
    public function function_Showtopthree(){ //不需要参数
        //数据初始化
        $commics = Commic::getByUpdatetopthree();
        if(empty($commics)){
            $content = '暂时没查到任何更新漫画';
            $data = array(
                '0' => 0, 
                '1' => $errorContent,
            );
            return $data;
        }
        $data = array(
            '0' => 1,
            '1' => $commics,
        );
        return $data;
    }

    //漫画更新列表显示
    public function function_Showupdate(){ //不需要参数
        //数据初始化
        $commics = Commic::getByUpdatetopten();
        if(empty($commics)){
            $content = '暂时没查到任何更新漫画';
            $data = array(
                '0' => 0, 
                '1' => $errorContent,
            );
            return $data;
        }
        $commics_info = $this->Deal_UpdateCommics($commics);
        $data = array(
            '0' => 1,
            '1' => $commics_info
        );
        return $data;
    }

    /****某一用户系列功能****/

    //用户点击收藏漫画
    //收藏标示
    public function function_Collect($postData){ //需要的参数cId、session
        //判断数据是否齐全
        if(empty($postData['cId'])){
             //当没有uId时的报错返回
            $content = "请输入cId";
            $data = array(
                '0' => -3,
                '1' => $content,
            );
            return $data;
        }
        //赋值
        $cId = $postData['cId'];       //漫画id
        $session = $postData['session']; //用户标识id
        $uId = BaseController::Check_session($session); //得出用户的uId
        if(!$uId){
            //当没有uId时的报错返回
            $content = "请登录再收藏";
            $data = array(
                '0' => 0,
                '1' => $content,
            );
            return $data;
        }
         $user_commic = array(
            'uId' => $uId, //用户id
            'cId' => $cId, //漫画id
        );
        //避免延迟重复点击收藏
        $user = UserCommic::checkByuIdcId($user_commic);
        if($user){
            $content = "此用户已收藏漫画";
            $data = array(
                '0' => 1,
                '1' => $content,
            );
            return $data;
        }
        //先检查数据库是否存在用户收藏这漫画的信息
        $user = UserCommic::checkByuId($uId);
        if(!empty($user)){
            //更新用户的state
            $user_result = UserCommic::updateOnState($user_commic);
        }else{ 
            //用户的收藏漫画录入数据库的信息
            //添加数据到usercommic
            $user_result = UserCommic::add($user_commic);
        }
        //此id漫画的收藏量+1
        $collect_result = Commic::updateCollection($cId);
        if(!$user_result){
            $content = '收藏失败，请重新尝试';
            $data = array(
                '0' => -1, 
                '1' => $content,
            );
            return $data;
        }
        $result = array(
            'collect' => true,
            'content' => '收藏成功',
        );
        $data = array(
            '0' => 1,
            '1' => $result,
        );
        return $data;
    }
    
    //取消收藏
    public function function_Uncollect($postData){ //需要的参数cId、session
        //判断数据是否齐全
        if(empty($postData['cId'])){
             //当没有uId时的报错返回
            $content = "请输入cId";
            $data = array(
                '0' => -3,
                '1' => $content,
            );
            return $data;
        }
        //数据初始化
        //接收数据
        $cId = $postData['cId'];       //漫画id
        $session = $postData['session']; //用户标识id
        $uId = BaseController::Check_session($session); //得出用户的uId
        //当没有uId时的报错返回
        if(!$uId){
            $content = "请登录再收藏";
            $data = array(
                '0' => 0,
                '1' => $content,
            );
            return $data;
        }
        //用户的收藏漫画录入数据库的信息
        $user_commic = array(
            'uId' => $uId, //用户id
            'cId' => $cId, //漫画id
        );
        //添加数据到usercommic
        $user_result = UserCommic::updateOffState($user_commic);
        //此id漫画的收藏量-1
        $collect_result = Commic::updateUnCollection($cId);
        if(!$user_result){
            $content = '取消收藏失败，请重新尝试';
            $data = array(
                '0' => -1, 
                '1' => $content,
            );
            return $data;
        }
        $result = array(
            'collect' => false,
            'content' => '取消收藏',
        );
        $data = array(
            '0' => 1,
            '1' => $result,
        );
        return $data;
    }

    //显示用户收藏的漫画
    //同时显示观看到的哪一部分并返回那一个url
    public function function_Showcollect($postData){ //需要的参数session
        //数据初始化
        //接收数据
        $session = $postData['session']; //用户标识id
        $uId = BaseController::Check_session($session); //得出用户的uId
        //当没有uId时的报错返回
        if(!$uId){
            $content = "请登录再查看你的收藏";
            $data = array(
                '0' => 0,
                '1' => $content,
            );
            return $data;
        }
        //根据uId搜索用户收藏了哪些漫画
        $commics_cid = UserCommic::getByuId($uId);
        if(empty($commics_cid)){
            $content = "你还没有收藏任何漫画，请去观看";
            $data = array(
                '0' => 0,
                '1' => $content,
            );
            return $data;
        }

        //根据cId漫画详细的信息 分别为cId、name、cover、最新看到哪一集
        $user_commics = $this->Deal_UserCommic($commics_cid, $uId);
        $data = array(
            '0' => 1,
            '1' => $user_commics,
        );
        return $data;
    }

    //用户观看历史显示
    public function function_Showhistory($postData){ //需要的参数session
        //数据初始化
        //接收数据
        $session = $postData['session']; //用户标识id
        $uId = BaseController::Check_session($session); //得出用户的uId
        //当没有uId时的报错返回
        if(!$uId){
            $content = "请登录再查看你的历史";
            $data = array(
                '0' => 0,
                '1' => $content,
            );
            return $data;
        }
        //根据uId搜索用户查看了哪些漫画
        $commics_record = CommicRecord::getAllByuId($uId);
        if(empty($commics_record)){
            $content = "你还没有查看如何漫画，请去观看";
            $data = array(
                '0' => 0,
                '1' => $content,
            );
            return $data;
        }
        //获取阅读过的漫画的名字、封面
        //同时添加一个”继续阅读“的按钮功能-形式：添加继续阅读的标签 拥有数组数据为：'cId'、'储存路径'、'uCReading'
        $commics_info = $this->Deal_CommicRecord($commics_record);
        $data = array(
            '0' => 1,
            '1' => $commics_info,
        );
        return $data;
    }

    //经晋康商量 得出用户每点击下一页或者第一页漫画时 则请求一次接口 返回cId: 、history:(如：1/12)
    public function function_Reading($postData){ //需要的参数session、cId、reading
         //判断数据是否齐全
        if(empty($postData['cId'])){
            //当没有uId时的报错返回
            $content = "请输入cId";
            $data = array(
                '0' => -3,
                '1' => $content,
            );
            return $data;
        }else if(empty($postData['reading'])){
            //当没有uId时的报错返回
            $content = "请输入reading";
            $data = array(
                '0' => -3,
                '1' => $content,
            );
            return $data;
        }
        //数据初始化
        //接收数据
        $session = $postData['session']; //用户标识id
        $cId = $postData['cId']; //漫画id
        $reading = $postData['reading']; //看到第几集
        $uId = BaseController::Check_session($session); //得出用户的uId
        //当没有uId时的报错返回
        if(!$uId){
            $content = "此用户没有登录，不需要记录历史";
            $result = array(
                'cId' => $cId,
                'content' => $content,
            );
            $data = array(
                '0' => 0, 
                '1' => $result,
            );
            return $data;
        }
            
        //每次阅读一集漫画就传一个历史过来格式：1/10
        $record = array(
            'uId' => $uId,
            'cId' => $cId,
            'uCReading' => $reading,
        );
        //先检查是否存在这个用户历史
        $check_user = CommicRecord::getHisByuIdcId($uId, $cId);
        //当不存在时，将历史加入数据库，同时增加阅读量
        if(empty($check_user)){
            $result = CommicRecord::add($record);
            Commic::updateReadcount($cId);
        }else{
            //更新用户阅读历史
            $result = CommicRecord::updateCReading($record);
        } 
        $result = true;
        if(!$result){
            $content = "请求数据失败，请刷新一遍再看";
            $data = array(
                '0' => -1,
                '1' => $content,
            );
            return $data;
        }
        //更新成功后返回一个状态码
        $result = array(
            'cId' => $cId,
            'content' => '阅读历史更新成功',
        );
        $data = array(
            '0' => 1,
            '1' => $result,
        );
        return $data;
    }   

    /********************/



    //上传漫画
	public function actionLoadcom(){

	}

    /******/
    //外置函数的使用
    /*****/
    //显示漫画集数的页面
    public function Deal_episode($cId, $saveurl, $episodes){
        if($episodes > 0){
            $episodes_info = array();
            for($i = 1; $i <= $episodes; $i++){
                $pages = CommicPages::getPages($cId, $i);
                $saveurl = $saveurl.$i.'/1.jpg';
                //每一话的名字
                $episodes_info[$i]['episodeName'] = $pages['cEpisodeName'];
                $episodes_info[$i]['saveurl'] = $saveurl;
                //每一话的页数
                $episodes_info[$i]['pages'] = $pages['cPages'];
            }
            return $episodes_info;
        }
        return false;
    }

    //处理漫画详细信息
    public function Deal_UserCommic($commics_cid, $uId){
        $user_commics = array();
        $i = 0;
        foreach ($commics_cid as $key) {
            $cId = $key['cId'];
            $commic_info = Commic::getInfoBycId($cId);
            $commic_record = CommicRecord::getHisByuIdcId($uId, $cId);
            //漫画的已更新集数
            $user_commics[$i] = $commic_info;
            $user_commics[$i]['cNowupdate'] = '更新到'.$commic_info['cNowupdate'].'话';
            //漫画已看到的地方
            if(empty($commic_record)){
                $user_commics[$i]['uCReading'] = '未开始观看';
            }else{
                $commic_record = explode('/', $commic_record['uCReading']);
                $episode = $commic_record['0'];
                $page = $commic_record['1'];
                $user_commics[$i]['uCReading'] = '看到第'.$episode.'话第'.$page.'页';
            }
            //下一个漫画+1
            $i++;
        }
        return $user_commics;
    }

    //处理漫画历史的漫画详细信息
    public function Deal_CommicRecord($commics_record){
        $commics_info = array();
        $i = 0;
        foreach ($commics_record as $key) {
            $cId = $key['cId'];
            //将漫画历史的集数页数进行分割
            $commic_record = explode('/', $key['uCReading']);
            $episode = $commic_record['0'];
            $page = $commic_record['1'];
            //获取漫画的名字和封面
            $commic_info = Commic::getRecordInfoBycId($cId);
            $pages = CommicPages::getPages($cId, $episode);
            $commics_info[$i]['commic']['cId'] = $cId;
            $commics_info[$i]['commic']['cName'] = $commic_info['cName'];
            $commics_info[$i]['commic']['cCover'] = $commic_info['cCover'];
            //漫画id
            $commics_info[$i]['readagain']['cId'] = $cId;
            //当前话名字
            $commics_info[$i]['readagain']['cEpisodeName'] = $pages['cEpisodeName'];
            //当前话数
            $commics_info[$i]['readagain']['episode'] = $episode;
            //当前页数
            $commics_info[$i]['readagain']['page'] = $page;
            //获取当前话的总页数
            $commics_info[$i]['readagain']['length'] = $pages['cPages'];
            //当前图片阅读的位置
            $commics_info[$i]['commic']['uCReading'] = '看到第'.$episode.'话第'.$page.'页';
            //漫画的储存路径
            $commics_info[$i]['readagain']['readurl'] = $commic_info['cSaveurl'].$episode.'/'.$page.'.jpg';
            $i++;
        }
        return $commics_info;
    }

    //单独处理某一漫画阅读历史
    public function Deal_OneCommicRecord($commics_record){
        $commics_info = array();
        $cId = $commics_record['cId'];
        //将漫画历史的集数页数进行分割
        $commic_record = explode('/', $commics_record['uCReading']);
        $episode = $commic_record['0'];
        $page = $commic_record['1'];
        //获取漫画的名字和封面、名字、页数
        $commic_info = Commic::getRecordInfoBycId($cId);
        $pages = CommicPages::getPages($cId, $episode);
        //当前话的名字
        $commics_info['episodeName'] = $pages['cEpisodeName'];
        //当前话数
        $commics_info['episode'] = $episode;
        //当前页数
        $commics_info['page'] = $page;
        //获取当前话的总页数
        $commics_info['length'] = $pages['cPages'];
        //当前图片阅读的位置
        $commics_info['uCReading'] = '看到第'.$episode.'话第'.$page.'页';
        //漫画的储存路径
        $commics_info['readurl'] = $commic_info['cSaveurl'].$episode.'/'.$page.'.jpg';
        return $commics_info;
    }

    //处理最新更新的漫画信息
    public function Deal_UpdateCommics($commics){
        $length = count($commics);
        for($i = 0; $i < $length; $i++){
            $episode = $commics[$i]['cNowupdate'];
            $commics[$i]['cNowupdate'] = '已更新到第'.$episode.'话';
        }
        return $commics;
    }
}